<?php
namespace Live\Model;
use Think\Model;

class UserModel extends Model {
	protected $_validate = array(
		array('username', 'require', '用户名不能为空', 0, 'regex', 1),
		array('username', 'checkUserName', '用户不存在', 0, 'callback', 1),
		array('password', 'require', '密码不能为空', 0, 'regex', 1),
		array('password', 'checkPwd', '密码错误', 0, 'callback', 1),

	);

	protected $_auto = array(
		array('password', 'md5', 1, 'function'),
		array('lastlogintime', 'time', 1, 'function'),
		array('lastloginip', 'get_client_ip', 1, 'function'),
	);

	/**
	 * 检查用户名
	 * @return [type] [description]
	 */
	public function checkUserName() {
		$username = I('post.username');

		$res = M('Admin')->where(array('username' => $username))->getField('id');
		if(!$res) {
			$condition['realname'] = $username;
			$condition['mobile'] = $username;
			$condition['_logic'] = 'OR';
			$res = M('UserInfo')->where($condition)->getField('uid');
		}

		if($res) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检查用户密码
	 * @return [type] [description]
	 */
	public function checkPwd() {
		$username = I('post.username');
		$password = I('post.password');

		// if($username == 'admin') {
		$map['username'] = trim($username);
		$map['password'] = md5(htmlspecialchars_decode(trim($password)));
		$res = M('Admin')->where($map)->find();

		if(!$res) {
			$condition['username'] = trim($username);
			$condition['mobile'] = trim($username);
			$condition['realname'] = trim($username);
			$condition['_logic'] = 'OR';
			$condition2['_complex'] = $condition;
			$condition2['password'] = md5(htmlspecialchars_decode(trim(C('PWD_SALT') . $password)));
			$res = $this->alias('u')->join('__USER_INFO__ as ui ON ui.uid = u.uid')->where($condition2)->find();

			if($res) {
				$this->lastloginip = get_client_ip();
				$this->lastlogintime = time();
				$this->where(array('uid' => $res['uid']))->save();
				$this->setLogin($res);
				return true;
			} else {
				return false;
			}			
		} else {
			$model = M('Admin');
			$model->lastloginip = get_client_ip();
			$model->lastlogintime = time();
			$model->where(array('id' => $res['id']))->save();
			$this->setLogin($res);
			return true;
		}	
	}

	/**
	 * 设置登录信息
	 * @param [type] $res [description]
	 */
	public function setLogin($array) {
        session('liveadmin_uid', isset($array['uid']) ? $array['uid'] : $array['id']);
		session('liveadmin_username', $array['username']);
		session('liveadmin_realname', $array['realname']);
		session('is_admin', isset($array['id']) ? 1 : 0);

		// session('auth_id', $array['authid']);
	}

}